<template>
  <h3>orders 医嘱</h3>
  <div class="h400 wb100">
    <f-table-plan ref="tablePlanRef" v-bind="gridOptions">
      <!-- 医嘱项目 -->
      <template #edit_name="{ row }">
        <div v-for="order in row?.orderInfos" :key="order.orderId">
          <f-follow-entrust
            v-model:value="order.name"
            :odType="row?.odType?.code"
            :odTimely="'2'"
            :visitInfo="{
              visitType: queryData?.visitType,
              visitId: queryData?.visitId
            }"
            :patientInfo="{ gender: '2', age: '4岁' }"
            @change="handleFollowSelected($event, row, order)" />
        </div>
      </template>
      <!-- 剂量 -->
      <template #edit_everyDose="{ row }">
        <div v-for="order in row?.orderInfos" :key="order.orderId" class="flex">
          <f-input-number v-model:value="order.everyDose" :min="0" :step="1" />
        </div>
      </template>
      <!-- 用法 -->
      <template #edit_usageName="{ row }">
        <!-- if 药品 -->
        <f-super-set
          v-model:value="row.usageId"
          v-bind="coluProps"
          :isDefault="false"
          :query="
            apiExtendUsages({
              isSignal: false,
              orderId: row?.orderId,
              usageType: row?.odType?.code,
              isSkintest: row?.orderInfos?.[0].skintestWork,
              isSkintestDrug: row?.orderInfos?.[0].skintestDrug
            })
          " />
      </template>
      <!-- 接收科室 -->
      <template #edit_receiveDeptName="{ row }">
        <!-- if 发药方式不为外购 -->
        <div v-for="order in row?.orderInfos" :key="order.orderId">
          <f-super-set
            v-model:value="order.receiveDeptId"
            v-bind="coluProps"
            :showSearch="false"
            :query="
              apiExtendOditemExec({
                isSignal: false,
                visitType: '11',
                oditemId: order.oditemId,
                usageId: row.usageId,
                patient: {}
              })
            " />
        </div>
      </template>
      <!-- 用药目的 -->
      <template #edit_abtPurpose="{ row }">
        <!-- if 药品 && 药品属性为抗菌 -->
        <div v-for="order in row?.orderInfos" :key="order.orderId">
          <f-dictionary
            class="w100%"
            dropdownClassName="vxe-table--ignore-clear"
            v-model:value="order.abtPurpose"
            :isDefault="true"
            :allowClear="true"
            code="abtPurpose" />
        </div>
      </template>
      <!-- 发药方式 -->
      <template #edit_dispensingMode="{ row }">
        <!-- if 药品 -->
        <div v-for="order in row?.orderInfos" :key="order.orderId">
          <f-dictionary
            class="w100%"
            dropdownClassName="vxe-table--ignore-clear"
            v-model:value="order.dispensingMode"
            :isDefault="true"
            :showSearch="false"
            :allowClear="true"
            code="DispensingMode" />
        </div>
      </template>
    </f-table-plan>
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { dayjs } from "fok-js";
import { http } from "../../packages/utils";

const queryData = ref({
  "visitId": "1860857585568931840",
  "visitType": "11",
  "status": "0",
  "diagnosisIds": ['1861290958263205888']
})

const gridOptions = ref({
  showOverflow: null,
  id: 'advice_enter_row',
  toolbarConfig: {
    search: false
  },
  rowConfig: {
    keyField: 'index',
    isHover: true
  },
  checkboxConfig: {
    labelField: 'index',
    showHeader: true
  },
  rowStyle({ row }: any) {
    return [true, 'true'].includes(row.isError) ? {
      backgroundColor: '#fdeced'
    } : {};
  },
  cellStyle() {
    return {
      padding: '1px 0'
    };
  },
  query: () => http.post('/clinical/orders/queryList', queryData.value).then((res: any) => ({
    ...res,
    data: res.data.map((m: any) => ({
      ...m,
      orderId: m?.id,
      odType: m?.orderInfos?.[0]?.odType, // 类别
      odTimely: m?.odTimely?.code, // 接收科室id
      odTimelyName: m?.odTimely?.desc, // 接收科室名称
      createTime: dayjs(m?.orderInfos?.[0]?.createTime).format("MM-DD HH:mm"),
      orderInfos: m.orderInfos.map((order: any) => ({
        ...order,
        bodyPart: order?.odItemViewCO?.bodyPart, // 部位信息
        drugInfo: order?.odItemViewCO?.drugInfo, // 药品信息
        specimen: order?.odItemViewCO?.specimen, // 检验样本
        odItemInfo: order?.odItemViewCO?.odItemInfo, // 医嘱项目
        name: order?.odItemName || order?.odItemViewCO?.odItemInfo?.odItemName
      }))
    }))
  })),
  columns: [
    { field: "createTime", title: "开嘱时间", width: 100, fixed: 'left', align: "right" },
    { field: 'name', title: '医嘱项目', width: 220, slots: { default: 'edit_name' } },
    { field: 'everyDose', title: '剂量', width: 80, align: "right", slots: { default: 'edit_everyDose' } },
    { field: 'usageName', title: '用法', width: 90, slots: { default: 'edit_usageName' } },
    { field: 'receiveDeptName', title: '接收科室', width: 180, slots: { default: 'edit_receiveDeptName' } },
    { field: 'abtPurposeName', title: '用药目的', width: 110, slots: { default: 'edit_abtPurpose' } },
    { field: 'dispensingModeName', title: '发药方式', width: 110, fixed: 'right', slots: { default: 'edit_dispensingMode' } },
  ]
})

// follow选择事件
const handleFollowSelected = (data: any, row: any, order: any) => {
  console.log('follow选择事件', data, row, order);
};

// 下拉选择框统一参数
const coluProps = {
  isModelValueChange: true,
  allowClear: true,
  isDefault: true,
  class: "w100%",
  dropdownClassName: "vxe-table--ignore-clear",
  fieldNames: { label: "name", key: "id" }
};

const useCachedFn = () => {
  const cachedMap: Record<string, { cachedFn: any; prevDepends: any[] }> = {};
  return (
    fn: () => Promise<any[]>,
    depends: any[] = [],
    key: string = "key"
  ) => {
    key = key + depends.join("");
    if (!cachedMap[key]) {
      cachedMap[key] = { cachedFn: null, prevDepends: [] };
    }

    cachedMap[key].cachedFn = fn;
    return cachedMap[key].cachedFn;
  };
};

const cached = useCachedFn();

// 用法
const apiExtendUsages = (data: any) =>
  cached(
    () =>
      http.post<any[]>(
        '/base/usages/getOrderUsages',
        http.adornParams(data)
      ).then((res) => (res.isSuccess ? res.data : [])),
    [data.orderId, data.usageType, data.isSkintest, data.isSkintestDrug],
    "usageName"
  );

// 执行科室
const apiExtendOditemExec = (data: any) =>
  cached(
    () =>
      http.post<any[]>(
        '/base/oditemexec/getExecInfo',
        http.adornParams(data)
      ).then((res) => res.isSuccess ? res.data?.map((m) => m.execDeptId) : []),
    [data.oditemId, data.usageId],
    "receiveDeptName"
  );
  
const changeDiagnosis = (items: any[]) => {
  console.log(items);
}

</script>

<style lang="scss"></style>
